/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2025-03-05     Lenovo       the first version
 */
#include <rtthread.h>
#include <rtdevice.h>
#include <string.h>
#include <board.h>
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <aht10.h>
#include <fengshan.h>
#include <jiashiqi.h>
#include <lengning.h>
#include <mensuo.h>
#include <LED.h>
#include <onenet.h>
// #define DBG_TAG "adc_uart"
// #define DBG_LVL         ADC_UART_DBG_LOG
#include <rtdbg.h>
#include <as608.h>

/* 配置 LED 灯引脚 */

#define PIN_LED_B              GET_PIN(F, 11)      // PF11 :  LED_B        --> LED
#define PIN_LED_R              GET_PIN(F, 12)      // PF12 :  LED_R        --> LED

#define REFER_VOLTAGE       5.0         /* 参考电压 5V,数据精度乘以100保留2位小数*/
#define CONVERT_BITS        (1 << 12)   /* 转换位数为12位 */
#define Q7_RL               1000.00     /* 单位：欧姆 */
#define Q7_R0               6.64
#define CAL_PPM             10.00
#define Q2_RL               1000.00       /* 单位：欧姆 */
#define LOAD_RESISTANCE     4700       /* 负载电阻，单位：Ω */
#define ADC_DEV_NAME "adc1"
/* UART配置 */
#define UART_DEV_NAME "uart3"
rt_device_t serial;
/* 接收缓冲区定义 */
#define UART_RX_BUF_SIZE    512
static char uart_rx_buf[UART_RX_BUF_SIZE];
static rt_size_t rx_len = 0;
static rt_bool_t cmd_recv_complete = RT_FALSE;

static rt_adc_device_t adc_dev;

static struct rt_semaphore rx_sem; //信号量
static struct rt_messagequeue cmd_mq; //消息队列
static char cmd_mq_pool[256];
/*串口接收回调函数*/
uint8_t rx3flag = 0;
uint8_t rx3counter = 0;
char rx3one;

void uart3_rx_callback(void *parameter)
{
    rt_device_read(serial, 0, &rx3one, 1);
    uart_rx_buf[rx3counter++] = rx3one;
    if (rx3counter > 512) {
        rx3counter = 0;
    }
    rx3flag = 1;
}

/* 传感器数据结构 */
struct sensor_data {
    double co_ppm;      // 一氧化碳
    double smoke_ppm;   // 烟雾
    double keran_baifenbi;     // 可燃气体百分比
    float temperature;  // 温度
    float humidity;     // 湿度
};

extern float Temp, Humi;

/* 设备控制初始化 */
int device_control_init(void)
{
    /* 初始化信号量 */
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
    LOG_D("Device control initialized");

    /* 初始化消息队列 */
    rt_mq_init(&cmd_mq, "cmd_mq", cmd_mq_pool, sizeof(char), sizeof(cmd_mq_pool), RT_IPC_FLAG_FIFO);

    /* 初始化UART3 */
    serial = rt_device_find(UART_DEV_NAME);
    if (!serial) {
        LOG_E("UART device [%s] not found!", UART_DEV_NAME);
        return 2;
    }

    /* 配置串口参数 */
    struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;
    config.baud_rate = BAUD_RATE_115200;  /* 设置波特率为115200 */
    config.data_bits = DATA_BITS_8;
    config.stop_bits = STOP_BITS_1;
    config.parity    = PARITY_NONE;
    config.bufsz     = 256;
    config.flowcontrol = 0;

    /* 应用配置 */
    rt_device_control(serial, RT_DEVICE_CTRL_CONFIG, &config);

    /* 设置接收回调函数 */
    //rt_device_set_rx_indicate(serial, uart_rx_ind);
    rt_device_set_rx_indicate(serial, uart3_rx_callback);

    /* 以中断接收模式打开串口 */
    if (rt_device_open(serial, RT_DEVICE_FLAG_INT_RX) != RT_EOK) {
        LOG_E("UART device open failed!");
        return RT_ERROR;
    }
    return RT_EOK;
}

/* ADC初始化 */
int adc_init(void)
{
    adc_dev = (rt_adc_device_t)rt_device_find(ADC_DEV_NAME);
    if (!adc_dev) {
        LOG_E("ADC device [%s] not found!", ADC_DEV_NAME);
        return -RT_ERROR;
    }

    /* 使能ADC通道 */
    rt_adc_enable(adc_dev, 0);  // PA0/Q7
    rt_adc_enable(adc_dev, 6);  // PA6/Q2
    rt_adc_enable(adc_dev, 4);  // PA4/Q9（根据实际硬件连接确认）

    return RT_EOK;
}

/* 读取并计算传感器数据 */
static void read_sensors(struct sensor_data *data)
{
    /* 读取原始ADC值 */
    rt_uint32_t q7_val = rt_adc_read(adc_dev, 0);
    rt_uint32_t q2_val = rt_adc_read(adc_dev, 6);
    rt_uint32_t q9_val = rt_adc_read(adc_dev, 4);

    /* 转换为电压值 */
    float q7_voltage = q7_val * REFER_VOLTAGE / CONVERT_BITS;
    float q2_voltage = q2_val * REFER_VOLTAGE / CONVERT_BITS;
    float q9_voltage = q9_val * REFER_VOLTAGE / CONVERT_BITS;

    /* 计算传感器电阻 */
    float q7_rs = (5.0f - q7_voltage) / (q7_voltage * 0.5);

    float q2_rs = Q2_RL * (5.0f - q2_voltage) / q2_voltage;
    float Q2_R0 = Q2_RL * (5 - 0.57) / 0.57;

    /* 转换为PPM值（根据传感器特性调整公式） */
    data->co_ppm = powf(11.5428 * Q7_R0 / q7_rs, 0.6549f);
    data->smoke_ppm = powf(21.72*Q2_R0/q2_rs, 2.1101f);
    data->keran_baifenbi = q9_voltage;  // 根据实际传感器添加计算公式
    data->temperature = Temp;
    data->humidity = Humi;
}

/* 向陶晶驰串口屏发送数据 */
static void send_data_to_touchscreen(const struct sensor_data *data)
{
    char buffer[256];
    /* 串口屏发送数据 */
    int len = snprintf(buffer, sizeof(buffer),
        "t1.txt=\"%.2f\"\xFF\xFF\xFF"
        "t13.txt=\"%.2f\"\xFF\xFF\xFF"
        "t3.txt=\"%.2f\"\xFF\xFF\xFF"
        "t19.txt=\"%.2f\"\xFF\xFF\xFF"
        "t18.txt=\"%.2f\"\xFF\xFF\xFF",
        data->co_ppm, data->smoke_ppm, data->keran_baifenbi, data->temperature, data->humidity);

    /* 通过串口发送数据 */
    if(len > 0 && serial)
    {
        rt_device_write(serial, 0, buffer, len);
    }
}

/* 处理接收到的命令 */
static void process_command(const char* cmd)
{

   //uart_rx_buf[rx_len] = '\0';  // 确保字符串以'\0'结尾

    rt_kprintf("Processing command: %s\n", cmd);

    /* 命令解析与处理 */
    if (strstr(cmd, "CCFAN_ON")  != 0) {//循环风扇
        CCFAN_On();
        LOG_I("CCFAN turned ON");
    }
    else if (strstr(cmd, "CCFAN_OFF") != 0) {
        CCFAN_Off();
        LOG_I("CCFAN turned OFF");
    }
    else if (strstr(cmd, "COFAN_ON") != 0) {//散热风扇
        COFAN_On();
        LOG_I("HMF turned ON");
    }
    else if (strstr(cmd, "COFAN_OFF")  != 0) {
        COFAN_Off();
        LOG_I("COFAN turned OFF");
    }
    else if (strstr(cmd, "RIGHT")  != 0) {//密码锁
        MenSuo_Off();
        LOG_I("MenSuo turned ON");
    }
    else if (strstr(cmd, "WRONG") != 0) {
        MenSuo_On();
        LOG_I("MenSuo turned OFF");
    }
    else if (strstr(cmd, "LED_ON") != 0) { //灯光
        LED_On();
        LOG_I("LED turned ON");
    }
    else if (strstr(cmd, "LED_OFF") != 0) {
        LED_Off();
        LOG_I("LED turned OFF");
    }
    else if (strstr(cmd, "RFR_ON") != 0) { //冷凝
        LENGNING_On();
        LOG_I("COLD ON");
    }
    else if(strstr(cmd, "RFR_OFF") != 0) {
        LENGNING_Off();
        LOG_I("COLD OFF");
    }
    else if (strstr(cmd, "HMF_ON") != 0) { //加湿
        JSQ_On();
        LOG_I("WATER ON");
    }
    else if(strstr(cmd, "HMF_OFF") != 0) {
        JSQ_Off();
        LOG_I("COLD OFF");
    }
    else {
        LOG_W("Unknown command: %s", cmd);
        return;  // 未知命令不更新状态
    }

    rx_len = 0;         // 清空接收缓冲区
    cmd_recv_complete = RT_FALSE; // 重置命令接收标志
}



/* 线程入口 */
void control_thread_entry(void *parameter)
{
    /* 主循环 */
    while (1) {

        if (rx3flag)
        {
            rt_kprintf("uart3 recv:%s\n",uart_rx_buf);
            /* 直接对比uart_rx_buf */
            //建议对比直接用strstr函数
            process_command(uart_rx_buf);

            rx3counter = 0;
            rx3flag = 0;
            memset(uart_rx_buf,0,512);
        }

        rt_thread_mdelay(10);
       }
}

void senddata_thread_entry(void *parameter)
{
rt_kprintf("thread3 entry...\n");
    struct sensor_data sensors;

    while(1)
    {                 //间隔

           read_sensors(&sensors);

             //格式化数据为字符串
//           int len = snprintf(buffer1, sizeof(buffer1),
//                "CO: %.2fppm, Smoke: %.2fppm, keran: %.2fppm, Tem: %f,Humi: %f\n",
//                sensors.co_ppm, sensors.smoke_ppm, sensors.keran_baifenbi, Temp, Humi);

    //        rt_kprintf("一氧化碳：%.2lfPPM。烟雾：%.2lfPPM。甲烷：%.2lfPPM。\r\n",sensors.co_ppm, sensors.smoke_ppm, sensors.ch4_ppm);

             //发送数据到串口屏
        send_data_to_touchscreen(&sensors);

        rt_thread_mdelay(3000);
        //rt_kprintf("send success\n");
    }
}

void onenet_thread_entry(void *parameter)
{
    struct sensor_data sensors;
    onenet_mqtt_init();
    onenet_mqtt_upload_digit("CO", sensors.co_ppm);
}
